package com.huli.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtils {
    //加密秘钥
    private final String secret = "f4e2e52834348asldjkfjlaksdjflkasjdflkjasldkfnlkxcnvlkjqalskdjfkasdflasjdf86b67cde581cof9eb5";
    //过期时间
    private final long expire = 5 * 60;
    private final String header = "Authorization";

    /**
     * 生成jwt token
     */
    public String generateToken(Integer userId) {
        Date now = new Date();

        //过期时间
        Date expireDate = new Date(now.getTime() + expire * 1000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId + "")
                .setIssuedAt(now)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();

    }

    // 获取jwt的信息
    public Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }
}

